package com.affectu.search.fetch;

import java.util.Date;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.Span;
import org.htmlparser.util.NodeList;

import com.affectu.search.Spider;
import com.affectu.search.fetch.thread.OutTaskThread;
import com.affectu.task.OuterTask;
import com.affectu.task.Task.Type;

/**
 * Oct 15, 2008
 * 
 * @author daniel nathan
 */
public class TaskCN extends OutTaskThread {

	private Spider spider = new Spider();

	public TaskCN() {
		super("http://www.taskcn.com/", "detail/index/id");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.affectu.search.fetch.task.FetchThread#spideSubpage(java.lang.String)
	 */
	@Override
	public OuterTask spideSubPage(String url) {
		OuterTask outTask = new OuterTask();
		String name = "";
		String tag = "";
		int budget = 0;
		String description = "";
		try {
			OrFilter allFilter = new OrFilter();
			allFilter.setPredicates(new NodeFilter[] {
					new NodeClassFilter(Div.class),
					new NodeClassFilter(Span.class) });
			NodeList nodeList = new Parser(url).parse(allFilter);
			for (Node node : nodeList.toNodeArray()) {

				String attributeValue;
				if (node instanceof Div) {
					Div divNode = (Div) node;
					attributeValue = divNode.getAttribute("class");
					if ("taskmoneyinfo fl nlink".equals(attributeValue)) {
						// ...得到金额(纯文本)
						String values = divNode.toHtml();
						this.log(values);
						String value = spider.fetchSpecificText(
								"中标所得：[0-9]*.00元", values).trim();
						budget = this.getIntValue(value);
						this.log("" + budget);

						String tagValue = spider.fetchSpecificText(
								"分类：[^_]*</a><", values).trim();
						tag = this.removeHtmlTags(tagValue.replaceAll(
								"任务序号：[0-9]+", ""));
					} else if ("taskdescription f12 bgreyline"
							.equals(attributeValue)) {
						// ...得到内容(纯文本)
						description = divNode.toHtml();
						this.log(description);
					}

				} else if (node instanceof Span) {
					Span spanNode = (Span) node;
					attributeValue = spanNode.getAttribute("class");
					if ("ffa".equals(attributeValue)) {
						name = spanNode.toPlainTextString();
						this.log(name);
					}

				}

			}// end for
			outTask.setId(System.currentTimeMillis());
			outTask.setName(name);
			outTask.setTag(tag);
			outTask.setBudget(budget);
			outTask.setDescription(description);
			outTask.setUrl(url);
			outTask.setType(Type.OUTER);
			outTask.setPublishDate(new Date());

		} catch (Exception ex) {
			this.logAffectuException(ex, "抓取子页出错 :" + url);
		}
		return outTask;
	}

}
